$(function() {

    function initTab(pageNum, pageSize) {
        pageNum = pageNum && pageNum > 0 ? pageNum : getCurPage();
        $.post('/project/page', { pageSize: pageSize > 0 ? pageSize : 10, pageNum: pageNum > 0 ? pageNum : 1 }, function(data) {
            if (data && data.retCode == 0) {
                var page = data.retVal;
                var proList = page.list;
                var html = '';
                var proInfo;
                var user = sessionStorage.getItem("account");
                for (var i = 0; i < proList.length; i++) {
                    proInfo = proList[i];
                    html += '<tr proId="' + proInfo.id + '">';
                    html += '<td>';
                    if (user == proInfo.creator) {
                        html += '<input type="checkbox" proId="' + proInfo.id + '">';
                    } else {
                        html += '<input type="checkbox" disabled>';
                    }
                    html += '</td>';
                    html += '<td>' + proInfo.name + '</td>';
                    html += '<td>';
                    if (proInfo.tag) {
                        proInfo.tag.split(',').forEach(function(e) {
                            html += '<span class="label label-success">' + e + '</span>&nbsp;';
                        });
                    }
                    html += '</td>';
                    html += '<td>' + proInfo.description + '</td>';
                    html += '<td>' + conv_time(proInfo.createTime, false) + '</td>';
                    html += '<td>' + conv_time(proInfo.updateTime, false) + '</td>';
                    html += '<td>' + '<span class="badge badge-info" style="background-color: #5BC0DE;">' + proInfo.creator + '</span>' + '</td>';
                    html += '<td>';
                    if (proInfo.users) {
                        proInfo.users.forEach(function(e, index) {
                            html += '<span class="badge badge-info" style="background-color: #5BC0DE;">' + e.account + '</span>&nbsp;';
                        });
                    }
                    html += '</td>';
                    html += '<td proId="' + proInfo.id + '">';
                    html += '<a name="detail">详情</a>';
                    if (user == proInfo.creator) {
                        html += '&nbsp;|&nbsp;<a name="transfer" >转移</a>' +
                            '&nbsp;|&nbsp;<a name="upd">编辑</a>' +
                            '&nbsp;|&nbsp;<a name="del">删除</a>';
                    }
                    html += '</td>';
                    html += '</tr>';
                }
                $('#proTable>tbody').empty().append(html);
                $("#selectBatch").get(0).checked = false;
                pageInit(page.pageNum, page.pages);
            }
        });
    }

    initTab();

    // 分页
    function pageInit(current, pages) {
        var options = {
            bootstrapMajorVersion: 3,
            currentPage: current > 0 ? current : 1,
            totalPages: pages > 0 ? pages : 1,
            numberOfPages: 5,
            itemTexts: function(type, page, current) { //文字翻译
                switch (type) {
                    case "first":
                        return "首页";
                    case "prev":
                        return "上一页";
                    case "next":
                        return "下一页";
                    case "last":
                        return "尾页";
                    case "page":
                        return page;
                }
            },
            pageUrl: '#',
            onPageClicked: function(event, originalEvent, type, page) {
                initTab(page);
            }
        };
        $(".pagination").bootstrapPaginator(options);
    }

    function getCurPage() {
        try {
            var page = $(".pagination .active").children('a').text();
            return page && page != '' ? page : 1;
        } catch (e) {
            return 1;
        }
    }

    // 批量选择
    $("#selectBatch").click(function(event) {
        if (this.checked) {
            $("#proTable>tbody :checkbox").each(function() {
                if (!this.disabled) {
                    this.checked = true;
                }
            });
        } else {
            $("#proTable>tbody :checkbox").each(function() {
                this.checked = false;
            });
        }
    });

    $('#proTable').on('click', 'tbody :checkbox', function(e) {
        if (!this.checked) {
            $("#selectBatch").get(0).checked = false;
        } else {
            var flag = false;
            $("#proTable>tbody :checkbox").each(function() {
                if (!this.checked) {
                    flag = true;
                    return;
                }
            });
            if (flag) {
                $("#selectBatch").get(0).checked = false;
            } else {
                $("#selectBatch").get(0).checked = true;
            }
        }
    });


    //批量删除
    $("#btnDelBatch").click(function(event) {
        var ids = new Array();
        $("#proTable>tbody :checked").each(function() {
            if (this.checked) {
                ids.push(this.getAttribute("proId"));
            }
        });
        if (ids.length > 0) {
            // jquey传递数组到后台，需要用“ids[]”获取，因此此处写成，ids[]
            $.post('/project/delete/batch', { 'ids[]': ids }, function(data, textStatus, xhr) {
                /*optional stuff to do after success */
                if (data && data.retCode == 0) {
                    $("#proTable>tbody :checked").parents("tr").remove();
                }
            });
        }
    });
    /*
        $('#userSearchInput').typeahead({
            source: function(query, process) {
                $.get('/user/queryByNameOrAccount?condition=' + query, function(data) {
                    if (data && data.retCode == 0) {
                        var users = new Array();
                        if (data.retVal) {
                            data.retVal.forEach(function(obj, index) {
                                users.push({
                                    id: obj.id,
                                    name: (obj.name == null ? '' : obj.name) + '(' + obj.account + ')'
                                })
                            });
                            process(users);
                        }
                    }
                });
            },
            autoSelect: true
        });

        $('#userTags').tagsinput({
            itemValue: 'id',
            itemText: 'name'
        });

        $("#userAddBtn").click(function(event) {
            // 新增用户
            // TODO 判断输入的是存在的用户
            var val = $('#userSearchInput').typeahead("getActive");

            $('#userTags').tagsinput('add', { id: val.id, name: val.name });
            $('#userSearchInput').val('');
        });
    */

    //新增
    $("#btnCreate").click(function(event) {
        //准备数据
        $("#updIdInput").val('');

        //打开对话框
        $('#create-modal').modal('show');
    });

    $('#createSave').click(function(event) {
        if (checkForm()) {
            var proObj = {
                id: $("#updIdInput").val(),
                name: $('#name').val(),
                tag: $('#tag').val(),
                description: $('#description').val(),
                userIds: $('#userTags').val()
            };
            if (proObj.id > 0) {
                $.post('/project/update', proObj, function(data, textStatus, xhr) {
                    if (data && data.retCode == 0) {
                        $('#create-modal').modal('hide');
                        createReset();
                        initTab();
                    }
                });
            } else {
                $.post('/project/create', proObj, function(data, textStatus, xhr) {
                    if (data && data.retCode == 0) {
                        $('#create-modal').modal('hide');
                        createReset();
                        initTab();
                    }
                });
            }
        } else {
            //TODO
        }
    });

    $('#createReset').click(function(event) {
        createReset();
    });

    function createReset() {
        $("#createHideRest").click();
        $('#tag').tagsinput('removeAll');
        $('#userTags').tagsinput('removeAll');
    }

    function checkForm() {
        var name = $('#name').val();
        if (null == name || name == 'undefined' || name == '') {
            return fasle;
        }
        return true;
    }

    // 详情
    $('#proTable').on('click', 'tbody a[name="detail"]', function(e) {
        //清理数据
        $('#detailName').text('');
        $('#detailTag').html('');
        $('#detailDesc').text('');
        $('#detailCreator').html('');
        $('#detailUsers').html('');
        var id = $(this).parent().attr("proId");
        // 准备数据
        $.get("/project/get/" + id, function(data) {
            if (data && data.retCode == 0) {
                var proInfo = data.retVal;
                $('#detailName').text(proInfo.name);
                $('#detailDesc').text(proInfo.description);
                $('#detailCreator').html('<span class="badge badge-info" style="background-color: #5BC0DE;">' + proInfo.creator + '</span>');
                var html = "";
                if (proInfo.tag) {
                    proInfo.tag.split(",").forEach(function(e, index) {
                        html += '<span class="label label-success">' + e + '</span>&nbsp;';
                    });
                    $('#detailTag').html(html);
                }
                if (proInfo.users) {
                    html = '';
                    proInfo.users.forEach(function(e, index) {
                        html += e ? '<span class="badge badge-info" style="background-color: #5BC0DE;">' +
                            (e.name == null || '' == e.name ? e.account : e.name) +
                            '</span>&nbsp;' : '';
                    });
                    $('#detailUsers').html(html);
                }
            }
        });
        //打开对话框
        $('#detail-modal').modal('show');
    });

    //权限转让
    $('#proTable').on('click', 'tbody a[name="transfer"]', function(e) {
        var id = $(this).parent().attr("proId");
        $("#transferTip").hide();
        $('#oldCreator').text(sessionStorage.getItem('account'));
        $('#transferIdInput').val(id);
        $('#newCreator').tagsinput('removeAll');
        $('#newCreator').val('');
        //打开对话框
        $('#transfer-modal').modal('show');
        $('#newCreator').tagsinput('focus');
        e.stopPropagation();
    });

    // 更新
    $('#proTable').on('click', 'tbody a[name="upd"]', function(e) {
        createReset();
        var self = $(this);
        var id = self.parent().attr("proId");
        // 准备数据
        $.get("/project/get/" + id, function(data) {
            if (data && data.retCode == 0) {
                var proInfo = data.retVal;
                $("#updIdInput").val(proInfo.id);
                $('#name').val(proInfo.name);
                proInfo.tag.split(",").forEach(function(element, index) {
                    $('#tag').tagsinput('add', element);
                });
                $('#description').val(proInfo.description);
                proInfo.users.forEach(function(e, index) {
                    $('#userTags').tagsinput('add', { id: e.id, name: (e.name == null ? '' : e.name) + '(' + e.account + ')' });
                });
            }
        });
        //打开对话框
        $('#create-modal').modal('show');
    });

    // 单个删除数据
    $('#proTable').on('click', 'tbody a[name="del"]', function(e) {
        var self = $(this);
        $.get('/project/delete/' + self.parent().attr('proId'), function(data) {
            if (data && data.retCode == 0) {
                self.parents("tr").remove();
            }
        });
    });

    //权限转让，搜索新用户控件
    $('#transferSave').click(function(event) {
        // 限制转一个用户
        var val = $('#newCreator').tagsinput('items')[0];
        var param = {
            projectId: $('#transferIdInput').val(),
            newOwnerId: val.id
        }
        if (val.account == sessionStorage.getItem('account')) {
            $("#transferTipContent").text('修改无变更');
            $("#transferTip").show();
            return false;
        }
        if (param && param.projectId > 0 && param.newOwnerId > 0) {
            $.post('/project/updateOwner', param, function(data) {
                if (data && data.retCode == 0) {
                    $('#transfer-modal').modal('hide');
                    // 为了去除&nbsp;
                    var manager = $('tbody td[proId="' + param.projectId + '"]');
                    var info = manager.children('a[name="detail"]');
                    manager.empty().html(info);

                }
            });
            $('#transfer-modal').modal('hide');
        } else {
            $("#transferTipContent").text('参数错误');
            $("#transferTip").show();
        }
    });


    var usersBH = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        prefetch: {
            url: '/user/queryByNameOrAccount?condition=%QUERY',
            filter: function(data) {
                if (data && data.retCode == 0) {
                    var users = new Array();
                    if (data.retVal) {
                        data.retVal.forEach(function(obj) {
                            users.push({
                                'id': obj.id,
                                'name': obj.name == null ? obj.account : obj.name + '(' + obj.account + ')',
                                'account': obj.account
                            });
                        });
                    }
                    return users;
                }
            }
        },
        remote: {
            url: '/user/queryByNameOrAccount?condition=%QUERY',
            wildcard: '%QUERY',
            filter: function(data) {
                if (data && data.retCode == 0) {
                    var users = new Array();
                    if (data.retVal) {
                        data.retVal.forEach(function(obj) {
                            users.push({
                                'id': obj.id,
                                'name': obj.name == null ? obj.account : obj.name + '(' + obj.account + ')',
                                'account': obj.account
                            });
                        });
                    }
                    return users;
                }
            }
        }
    });

    usersBH.initialize();

    /**
     * 权限转移，成员控件初始化。
     */
    $('#newCreator').tagsinput({
        tagClass: function(item) {
            return (item.length > 10 ? 'big' : 'small') + ' badge badge-info badge-blue label label-warning';
        },
        itemValue: 'id',
        itemText: 'name',
        autoSelect: false,
        maxTags: 1,
        typeaheadjs: {
            classNames: { input: 'Typeahead-input' },
            name: 'users',
            value: 'id',
            display: 'name',
            source: usersBH.ttAdapter()
        }
    });

    /**
     * 成员管理:新增修改项目时使用
     */
    $('#userTags').tagsinput({
        tagClass: function(item) {
            return (item.length > 10 ? 'big' : 'small') + ' badge badge-info badge-blue label label-warning';
        },
        itemValue: 'id',
        itemText: 'name',
        autoSelect: true,
        typeaheadjs: {
            classNames: { input: 'Typeahead-input' },
            name: 'users',
            value: 'id',
            display: 'name',
            source: usersBH.ttAdapter()
        }
    });

    $("#newCreator,#userTags").parent().on('keydown', '.tt-input', function() {
        $(this).attr('size', getByteLength($(this).attr('placeholder')));
    });
    $("#newCreator,#userTags").parent().on('beforeItemAdd itemRemoved ', function() {
        var self = $('.tt-input');
        self.attr('size', getByteLength(self.attr('placeholder')));
    });

});